#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int main ()
{
    //存储管道的文件描述符
    int pipefd[2];
    //父进程要发送的消息
    char message[] ="I am father";   
    pid_t pid;

    //创建匿名管道
    if(pipe(pipefd) == -1)
    {
        perror("pipe");
        return 1;
    }

    //创建子进程
    pid = fork();
    //创建失败，报错，关闭匿名管道
    if(pid == -1)
    {
        perror("fork");
        close(pipefd[0]);
        close(pipefd[1]);
        return 1;
    }
    //创建成功,子进程执行代码
    if(pid==0)
    {
      close(pipefd[1]);//子进程不需要写duan   
      //从管道读取数据
      char buffer[256];
      ssize_t bytes_read =read(pipefd[0],buffer,sizeof(buffer)-1);
      if(bytes_read>0)
      {
        buffer[bytes_read]='\0';//确保字符串以\0结尾
        printf("%s\n",buffer);
      }
      close(pipefd[0]);//关闭读端
    }
    else
    {
        //父进程
        close(pipefd[0]);//父进程不需要读端
        //向管道写入数据
        write(pipefd[1],message,strlen(message));
        close(pipefd[1]);//关闭写端
        //等待子进程结束
        wait(NULL);
    }
    return 0;
}